package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonStorageFeeMonth;
import com.fowo.api.entity.TmpStorageFeeMonth;
import com.fowo.api.mapper.AmazonStorageFeeMonthMapper;
import com.fowo.api.mapper.TmpStorageFeeMonthMapper;
import com.fowo.api.syncAmazon.api.StorageFeeMonthReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StorageFeeMonthServiceImpl extends ServiceImpl<AmazonStorageFeeMonthMapper, AmazonStorageFeeMonth> {

    @Resource
    private TmpStorageFeeMonthMapper tmpStorageFeeMonthMapper;
    @Resource
    private StorageFeeMonthReportService storageFeeMonthReportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    @Transactional(rollbackFor = Exception.class)
    public void syncStorageFeeMonth() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllStorageFeeMonth();
        //拉取数据到临时表
        storageFeeMonthReportService.getStorageFeeMonth();
        //获取临时表数据
        List<TmpStorageFeeMonth> feeMonths = tmpStorageFeeMonthMapper.selectList(new QueryWrapper<TmpStorageFeeMonth>().eq("del_flag", 0));
        List<AmazonStorageFeeMonth> insertList = new ArrayList<>();
        if (feeMonths != null && feeMonths.size() > 0) {
            for (TmpStorageFeeMonth feeMonth : feeMonths) {
                QueryWrapper<AmazonStorageFeeMonth> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("del_flag",0);
                orderWrapper.eq("sid",feeMonth.getSid());
                orderWrapper.eq("fnsku",feeMonth.getFnsku());
                orderWrapper.eq("month_of_charge",feeMonth.getMonthOfCharge());
                int count = (int)this.count(orderWrapper);
                if(count > 0){
                    continue;
                }
                AmazonStorageFeeMonth storageFeeMonth = new AmazonStorageFeeMonth();
                BeanUtils.copyProperties(feeMonth, storageFeeMonth);
                storageFeeMonth.setId(null);
                storageFeeMonth.setCreateTime(new Date());
                storageFeeMonth.setLastUpdateTime(new Date());
                insertList.add(storageFeeMonth);
            }
            List<List<AmazonStorageFeeMonth>> partition = Lists.partition(insertList, 200);
            for (List<AmazonStorageFeeMonth> list : partition) {
                this.saveBatch(list);
            }
        }
    }

}
